package com.lmc.forum.services.impl;

import ch.qos.logback.classic.Logger;
import com.lmc.forum.common.AppResult;
import com.lmc.forum.common.ResultCode;
import com.lmc.forum.dao.UserMapper;
import com.lmc.forum.exception.ApplicationException;
import com.lmc.forum.model.User;
import com.lmc.forum.services.IUserService;
import com.lmc.forum.utils.CryptoUtil;
import com.lmc.forum.utils.StringUtil;
import com.lmc.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        if (user == null) {
//            log.warn("用户信息为空"+ ResultCode.FAILED_USER_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL.getMessage()));
        }
//      查询用户名是否重复
        User existUser = userMapper.selectUserByUsername(user.getUsername());
        if (existUser != null) {
            log.warn(ResultCode.AILED_USER_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS.getMessage()));
        }
        // 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
// 性别赋默认值
            user.setGender((byte) 2);
        }
// 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.getMessage() + "username=" + user.getUsername());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE.getMessage()));
        }
        log.info("用户注册成功 username=" + user.getUsername());
    }

    @Override
    public User selectUserByUsername(String username) {
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage() + "用户名为空");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()));
        }
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public User login(String username, String password) {
        User user = selectUserByUsername(username);
        if (user == null) {
// 1. 用户不存在
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
// 2. 返回错误信息
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String encryptPassword = CryptoUtil.md5Salt(password, user.getSalt());
        if (!user.getPassword().equals(encryptPassword)) {
// 1. 密码错误
            log.info(ResultCode.FAILED_LOGIN.toString());
// 2. 错误信息
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectUserById(Long id) {
        if (id == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()));
        }

        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印⽇志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
// 打印⽇志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
// 查询⽤⼾信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
// 打印⽇志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
// 更新⽤⼾的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
// 判断减1之后，⽤⼾的发帖数是否⼩于0
        if (updateUser.getArticleCount() < 0) {
// 如果⼩于0，则设置为0
            updateUser.setArticleCount(0);
        }
// 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public User selectById(Long Id) {
        return userMapper.selectByPrimaryKey(Id);
    }

    @Override
    public void modifyInfo(User user) {
        // 1. ⾮空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
// 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
// 2. 校验⽤⼾是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
// 打印⽇志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
// 3. 定义⼀个标志位
        boolean checkAttr = false; // false表⽰没有校验通过
// 4. 定义⼀个专⻔⽤来更新的对象，防⽌⽤⼾传⼊的User对象设置了其他的属性
// 当使⽤动态SQL进⾏更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
// 5. 设置⽤⼾Id
        updateUser.setId(user.getId());
// 6. 对每个⼀个参数进⾏校验并赋值
        if (!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())) {
// 需要更新⽤⼾名(登录名)时，进⾏唯⼀性的校验
            User checkUser = userMapper.selectUserByUsername(user.getUsername());
            if (checkUser != null) {
// ⽤⼾已存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
// 抛出异常
                throw new
                        ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
// 数据库中没有找到相应的⽤⼾，表⽰可以修改⽤⼾名
            updateUser.setUsername(user.getUsername());
            // 更新标志位
            checkAttr = true;

    }
        // 7. 校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
// 设置昵称
            updateUser.setNickname(user.getNickname());
// 更新标志位
            checkAttr = true;
        }
// 8. 校验性别
        if (user.getGender() != null && user.getGender() !=
                existsUser.getGender()) {
// 设置性别
            updateUser.setGender(user.getGender());
// 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
// 更新标志位
            checkAttr = true;
        }
// 9. 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
// 设置邮箱
            updateUser.setEmail(user.getEmail());
// 更新标志位
            checkAttr = true;
        }
// 9. 校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
// 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
// 更新标志位
            checkAttr = true;
        }
// 10. 校验个⼈简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
// 设置电话号码
            updateUser.setRemark(user.getRemark());
// 更新标志位
            checkAttr = true;
        }
// 11. 根据标志位来决定是否可以执⾏更新
        if (checkAttr == false) {
// 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
// 12. 调⽤DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        // 1. 根据⽤⼾Id查询⽤⼾信息
        User user = userMapper.selectByPrimaryKey(id);
// 2. 校验⽤⼾Id是否有存在
        if (user == null) {
// 记录⽇志
            log.info(ResultCode.FAILED_UNAUTHORIZED.toString() + "user id = " + id);
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
// 3. 校验原密码是否正确
        String oldEncryptPassword = CryptoUtil.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
// 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "username = "
                    + user.getUsername() + ", password = " + oldPassword);
// 密码不正确抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
// 4. 重新⽣成扰动字符串
        String salt = UUIDUtil.UUID_32();
// 5. 计算新密码
        String encryptPassword = CryptoUtil.md5Salt(newPassword, salt);
// 6. 创建⽤于更新的User对象
        User modifyUser = new User();
// 设置⽤⼾Id
        modifyUser.setId(user.getId());
// 设置新密码
        modifyUser.setPassword(encryptPassword);
// 设置扰动字符串
        modifyUser.setSalt(salt);
// 设置更新时间
        modifyUser.setUpdateTime(new Date());
// 7. 更新操作
        userMapper.updateByPrimaryKeySelective(modifyUser);
// 打印⽇志
        log.info("⽤⼾密码修改成功：" + user.getUsername());
    }
}
